using JGSY.CMS.LowCode.Platform.Domain.Entities;
using JGSY.CMS.LowCode.Platform.Domain.Interfaces;
using JGSY.CMS.LowCode.Platform.Infrastructure.CmsDbContext;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace JGSY.CMS.LowCode.Platform.Infrastructure.Repositories
{
    /// <summary>
    /// 用户角色关联仓储实现
    /// 提供用户与角色关联关系管理的数据访问功能实现，使用Entity Framework进行数据持久化
    /// </summary>
    public class UserRoleRepository : IUserRoleRepository
    {
        private readonly LowCodeDbContext _context;

        public UserRoleRepository(LowCodeDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 获取所有用户角色关联关系
        /// </summary>
        /// <returns>用户角色关联关系列表</returns>
        public async Task<IEnumerable<UserRole>> GetAllAsync()
        {
            return await _context.UserRoles
                .Include(ur => ur.User)
                .Include(ur => ur.Role)
                .ToListAsync();
        }

        /// <summary>
        /// 添加用户角色关联关系
        /// </summary>
        /// <param name="entity">用户角色关联实体</param>
        /// <returns>添加操作的异步任务</returns>
        public async Task AddAsync(UserRole entity)
        {
            // 检查关联关系是否已存在，避免重复添加
            var exists = await _context.UserRoles
                .AnyAsync(ur => ur.UserId == entity.UserId && ur.RoleId == entity.RoleId);

            if (!exists)
            {
                await _context.UserRoles.AddAsync(entity);
                await _context.SaveChangesAsync();
            }
        }

        /// <summary>
        /// 移除用户角色关联关系
        /// </summary>
        /// <param name="userId">用户标识符</param>
        /// <param name="roleId">角色标识符</param>
        /// <returns>移除操作的异步任务</returns>
        public async Task RemoveAsync(long userId, long roleId)
        {
            var userRole = await _context.UserRoles
                .FirstOrDefaultAsync(ur => ur.UserId == userId && ur.RoleId == roleId);

            if (userRole != null)
            {
                _context.UserRoles.Remove(userRole);
                await _context.SaveChangesAsync();
            }
        }

        /// <summary>
        /// 获取用户的所有角色
        /// </summary>
        /// <param name="userId">用户标识符</param>
        /// <returns>用户拥有的角色列表</returns>
        public async Task<IEnumerable<Role>> GetRolesByUserAsync(long userId)
        {
            return await _context.UserRoles
                .Where(ur => ur.UserId == userId)
                .Select(ur => ur.Role!)
                .ToListAsync();
        }

        /// <summary>
        /// 获取指定角色的所有用户
        /// </summary>
        /// <param name="roleId">角色标识符</param>
        /// <returns>拥有该角色的用户列表</returns>
        public async Task<IEnumerable<User>> GetUsersByRoleAsync(long roleId)
        {
            return await _context.UserRoles
                .Where(ur => ur.RoleId == roleId)
                .Select(ur => ur.User!)
                .ToListAsync();
        }

        /// <summary>
        /// 检查用户是否拥有指定角色
        /// </summary>
        /// <param name="userId">用户标识符</param>
        /// <param name="roleId">角色标识符</param>
        /// <returns>如果用户拥有该角色返回true，否则返回false</returns>
        public async Task<bool> UserHasRoleAsync(long userId, long roleId)
        {
            return await _context.UserRoles
                .AnyAsync(ur => ur.UserId == userId && ur.RoleId == roleId);
        }

        /// <summary>
        /// 检查用户是否拥有指定角色名称的角色
        /// </summary>
        /// <param name="userId">用户标识符</param>
        /// <param name="roleName">角色名称</param>
        /// <returns>如果用户拥有该角色返回true，否则返回false</returns>
        public async Task<bool> UserHasRoleAsync(long userId, string roleName)
        {
            return await _context.UserRoles
                .Where(ur => ur.UserId == userId)
                .AnyAsync(ur => ur.Role!.Name == roleName);
        }

        /// <summary>
        /// 批量为用户分配角色
        /// </summary>
        /// <param name="userId">用户标识符</param>
        /// <param name="roleIds">角色标识符集合</param>
        /// <returns>批量分配操作的异步任务</returns>
        public async Task AssignRolesToUserAsync(long userId, IEnumerable<long> roleIds)
        {
            // 获取用户当前拥有的角色
            var existingRoleIds = await _context.UserRoles
                .Where(ur => ur.UserId == userId)
                .Select(ur => ur.RoleId)
                .ToListAsync();

            // 找出需要添加的新角色
            var newRoleIds = roleIds.Except(existingRoleIds);

            // 批量添加新的用户角色关联
            var newUserRoles = newRoleIds.Select(roleId => new UserRole
            {
                UserId = userId,
                RoleId = roleId
            });

            await _context.UserRoles.AddRangeAsync(newUserRoles);
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 移除用户的所有角色
        /// </summary>
        /// <param name="userId">用户标识符</param>
        /// <returns>移除操作的异步任务</returns>
        public async Task RemoveAllRolesFromUserAsync(long userId)
        {
            var userRoles = await _context.UserRoles
                .Where(ur => ur.UserId == userId)
                .ToListAsync();

            _context.UserRoles.RemoveRange(userRoles);
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 更新用户的角色分配
        /// 先移除所有现有角色，然后分配新角色
        /// </summary>
        /// <param name="userId">用户标识符</param>
        /// <param name="roleIds">新的角色标识符集合</param>
        /// <returns>更新操作的异步任务</returns>
        public async Task UpdateUserRolesAsync(long userId, IEnumerable<long> roleIds)
        {
            // 移除现有的所有角色
            await RemoveAllRolesFromUserAsync(userId);

            // 分配新角色
            if (roleIds.Any())
            {
                await AssignRolesToUserAsync(userId, roleIds);
            }
        }
    }
}
